package org.springblade.oa.controller;

import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.oa.service.IStatisticsService;
import org.springblade.system.entity.Dept;
import org.springblade.system.entity.Dict;
import org.springblade.system.feign.IDictClient;
import org.springblade.system.feign.ISysClient;
import org.springblade.system.user.entity.UserInfo;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("statistics")
@AllArgsConstructor
public class StatisticsController {
	/**
	 * 统计
	 * zhangxl 2020-01-21
	 */

	private IStatisticsService statisticsService;

	IDictClient dictClient;
	ISysClient sysClient;
	IUserClient userClient;

	/**
	 * 统计图数据
	 */
	@RequestMapping("/getExpenditureValue")
	@ApiOperation(value = "统计", notes = "统计")
	public R getExpenditureValue(@RequestParam String sjlx,//时间类型 （0：月，1：年）
								 @RequestParam String time,//起止时间（2020-01,2020-06）（2010,2020）
								 @RequestParam String bxdw, //报销单位
								 @RequestParam String bmid, //部门id
								 @RequestParam String xmid //项目id
	) {
//		localhost:8200/statistics/getExpenditureValue?sjlx=&time=&bxdw=&bmid=&xmid=
//		localhost/blade-oa/statistics/getExpenditureValue?sjlx=&time=&bxdw=&bmid=&xmid=
//		bxdw = "";
//		sjlx = "1";
//		bmid = "4";
//
//		if ("0".equals(sjlx))
//			time = "2020-01,2020-06";//"0" 时间类型（2020-01,2020-06）
//		else if ("1".equals(sjlx))
//			time = "2010,2020";//"1" 时间类型（2010,2020）

		SimpleDateFormat sdfn = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfy = new SimpleDateFormat("yyyy-MM");

		//返回数据
		Map<String, Object> rmap = new HashMap<>();

		List<Map<String, Object>> slst = new ArrayList<>();//扇形数据
		List<Map<String, Object>> sxsj = new ArrayList<>();//费用,差旅扇形数据
		Map<String, Object> tmap = new HashMap<>();//柱状数据
		Map<String, Object> clmap = new HashMap<>();//差旅柱状图
		Map<String, Object> zmap = new HashMap<>();//折线数据
		Map<String, Object> fyMap = new HashMap<>();//费用数据

		rmap.put("sx", slst);//扇形数据
		rmap.put("zz", tmap);//柱状数据
		rmap.put("zx", zmap);//折线数据
		rmap.put("fy", fyMap);//费用柱形数据
		rmap.put("ss", sxsj);//费用,差旅扇形数据
		rmap.put("cl", clmap);//差旅柱状图


		try {
			System.out.println("时间类型	\t\t" + sjlx);
			System.out.println("起止时间	\t\t" + time);
			System.out.println("报销单位	\t\t" + bxdw);
			System.out.println("部门id 	\t\t" + bmid);
			System.out.println("项目id	\t\t" + xmid);

			//时间格式化
			List<String> tmes = new ArrayList<>();//时间范围
			String stime = "", etime = "";//起止时间
			if (time != null && !"".equals(time)) {
				time = time.replace("，", ",");

				if (time.contains(",")) {
					String[] times = time.split(",");

					stime = times[0];
					etime = times[1];
				}

				Calendar c = Calendar.getInstance();

				if ("0".equals(sjlx)) { //时间类型（2020-01,2020-06）
					c.setTime(sdfy.parse(stime));
					while (c.getTimeInMillis() <= sdfy.parse(etime).getTime()) {
						tmes.add(sdfy.format(c.getTime()));
						c.add(Calendar.MONTH, 1);//+1月
					}
				} else if ("1".equals(sjlx)) { //时间类型（2010,2020）
					c.setTime(sdfn.parse(stime));
					while (c.getTimeInMillis() <= sdfn.parse(etime).getTime()) {
						tmes.add(sdfn.format(c.getTime()));
						c.add(Calendar.YEAR, 1);//+1年
					}
				} else {
					return R.data(200, rmap, "param error :sjlx" + sjlx);
				}
			} else {
				return R.data(200, rmap, "时间范围为空" + time);
			}

			//组装 时间范围 SQL
			StringBuilder tsb = new StringBuilder();
			if (tmes.size() > 0) {
				tsb.append("(");
				for (int i = 0; i < tmes.size(); i++) {
					tsb.append("'" + tmes.get(i) + "'");

					if (i < tmes.size() - 1)
						tsb.append(",");
				}
				tsb.append(")");
			}

			//数据类型 0：部门，1：项目
			String dtlx = "0";
			if (bmid != null && !"".equals(bmid))
				dtlx = "1";

			//sql 参数
			Map<String, Object> pmp = new HashMap<>();
			pmp.put("sjlx", sjlx);//时间类型 （0：月，1：年）
			pmp.put("dtlx", dtlx);//数据类型 （0：部门，1：项目）
			pmp.put("gsid", bxdw);//公司id
			pmp.put("bmid", bmid);//部门ID
			pmp.put("xmid", xmid);//项目ID
			pmp.put("sjfw", tsb.toString());//时间范围

			//有数据的 部门 或 项目
			Map<String, String> ismp = new HashMap<>();
			for (int i = 0; i < 3; i++) {
				if (i == 0) { //报销费用明细表
					pmp.put("glbm", "blade_oa_bxfymx");//关联表名
					pmp.put("sjzd", "d.create_time");//时间字段
				} else if (i == 1) { //报销行程明细表
					pmp.put("glbm", "blade_oa_bxxcmx");//关联表名
					pmp.put("sjzd", "d.kssj");//时间字段
				} else if (i == 2) { //报销住宿专票明细表
					pmp.put("glbm", "blade_oa_bxzszpmx");//关联表名
					pmp.put("sjzd", "d.kssj");//时间字段
				}

				List<Map<String, Object>> ilst = statisticsService.getBmidOrXmid(pmp);

				for (Map<String, Object> mp : ilst) {
					ismp.put(mp.get("id").toString(), mp.get("name").toString());
				}
			}

			Double sum=0.00;
			//扇形数据
			double val1 = 0.0;
			double val2 = 0.0;
			for (String str : ismp.keySet()) {
				if (bmid != null && !"".equals(bmid))
					pmp.put("xmid", str);//项目ID
				else
					pmp.put("bmid", str);//部门ID

				String val = "0.00";
				List<Map<String, Object>> ilst = statisticsService.getSXdata(pmp);
				List<Map<String, Object>> ilst1 = statisticsService.getSdata(pmp);

				if (ilst != null && ilst.size() > 0) {
					val = ilst.get(0).get("je").toString();
					sum=sum+Double.parseDouble(val);
				}

				if (ilst1 != null && ilst1.size() > 0) {
					val1 += Double.parseDouble(ilst1.get(0).get("je").toString());
					val2 += Double.parseDouble(ilst1.get(0).get("xj").toString());
				}
				Map<String, Object> mp = new HashMap<>();
				if (!"0.00".equals(val)){
					mp.put("name", ismp.get(str));
					mp.put("value", val);
				}
				slst.add(mp);
			}
			rmap.put("sxSum",sum);

			//费用,差旅扇形数据
			String douStr = String.format("%.2f", val1);
			String douStr1 = String.format("%.2f", val2);
			Map<String, Object> map1 = new HashMap<>();
			map1.put("name", "费用");
			map1.put("value", douStr);
			Map<String, Object> map2 = new HashMap<>();
			map2.put("name", "差旅");
			map2.put("value", douStr1);
			sxsj.add(map1);
			sxsj.add(map2);



			//差旅柱状图
			List<String> clst = null;
			List<Map<String, Object>> clt = new ArrayList<>();
			Double clSum=0.00;
			for (String str : ismp.keySet()) {
				if (bmid != null && !"".equals(bmid))
					pmp.put("xmid", str);//项目ID
				else
					pmp.put("bmid", str);//部门ID

				String val = "0.00";
				clst = new ArrayList<>();
				for (String sj : tmes) { //时间
					val = "0.00";
					pmp.put("sjfw", "('" + sj + "')");//时间范围
					List<Map<String, Object>> ilst = statisticsService.getCLdata(pmp);

					if (ilst != null && ilst.size() > 0) {
						val = ilst.get(0).get("je").toString();
						clSum=clSum+Double.parseDouble(val);
					}
					clst.add(val);
				}
				Map<String, Object> mp = new HashMap<>();
				mp.put("name", ismp.get(str));
				mp.put("data", clst);
				clt.add(mp);
			}
			clmap.put("x", tmes);
			clmap.put("series", clt);
			clmap.put("clSum",clSum);



				//柱状数据
			List<String> zvlst = null;
			List<Map<String, Object>> zlt = new ArrayList<>();
			for (String str : ismp.keySet()) {
				if (bmid != null && !"".equals(bmid))
					pmp.put("xmid", str);//项目ID
				else
					pmp.put("bmid", str);//部门ID

				String val = "0.00";

				zvlst = new ArrayList<>();
				for (String sj : tmes) { //时间
					val = "0.00";
					pmp.put("sjfw", "('" + sj + "')");//时间范围
					List<Map<String, Object>> ilst = statisticsService.getSXdata(pmp);

					if (ilst != null && ilst.size() > 0)
						val = ilst.get(0).get("je").toString();

					zvlst.add(val);
				}

				Map<String, Object> mp = new HashMap<>();
				mp.put("name", ismp.get(str));
				mp.put("data", zvlst);

				zlt.add(mp);
			}
			tmap.put("x", tmes);
			tmap.put("series", zlt);
			//柱状图支出汇总
			ArrayList<Double> sumList = new ArrayList<>(); //柱状每月的各部门总报销
			for(int j=0;j<zlt.size();j++){
				List<String> list = (List)zlt.get(j).get("data");
				for (int i = 0; i <list.size() ; i++) {
					if(j==0){
						sumList.add(0.00d);
					}
					sumList.set(i,sumList.get(i)+Double.valueOf(list.get(i).toString()));
				}
			}
			ArrayList<String> zzSumList = new ArrayList<>();
			for(Double d:sumList){
				zzSumList.add(String.format("%.2f",d));
			}
			rmap.put("zzSumList",zzSumList);


			//费用汇总柱状图
			ArrayList<Object> fyList = new ArrayList<>();
			List<Dict> costType = dictClient.getList("bx_costtype").getData();

			Double fySum=0.00;
			for (int i = 0; i < costType.size(); i++) {
				pmp.put("bmid", bmid);
				pmp.put("xmid", xmid);
				HashMap<String, Object> map = new HashMap<>();
				pmp.put("costType",costType.get(i).getDictKey());

				ArrayList<Object> lxList = new ArrayList<>();//相同类型在不同月份金额的集合
				String val = "0.00";
				for (String sj : tmes) { //时间
					val = "0.00";
					pmp.put("sjfw", "('" + sj + "')");//时间范围
					List<Map<String, Object>> lx = statisticsService.getfyData(pmp);
					if (lx.get(0) != null && lx.get(0).size() > 0) {
						val =lx.get(0).get("je").toString();
						fySum=fySum+Double.parseDouble(val);
					}
					lxList.add(val);
				}
				map.put("name",costType.get(i).getDictValue());
				map.put("data",lxList);
				fyList.add(map);
			}
			fyMap.put("series",fyList);
			fyMap.put("fySum",fySum);




			//折线数据
			List<String> zxlst = null;
			List<Map<String, Object>> zxlt = new ArrayList<>();
			for (String str : ismp.keySet()) {
				if (bmid != null && !"".equals(bmid))
					pmp.put("xmid", str);//项目ID
				else
					pmp.put("bmid", str);//部门ID

				String val = "0.00";

				zxlst = new ArrayList<>();
				for (String sj : tmes) { //时间
					val = "0.00";
					pmp.put("sjfw", "('" + sj + "')");//时间范围
					List<Map<String, Object>> ilst = statisticsService.getSXdata(pmp);

					if (ilst != null && ilst.size() > 0)
						val = ilst.get(0).get("je").toString();

					zxlst.add(val);
				}

				Map<String, Object> mp = new HashMap<>();
				mp.put("name", ismp.get(str));
				mp.put("data", zxlst);

				zxlt.add(mp);
			}
			tmap.put("x", tmes);
			tmap.put("series", zxlt);



		} catch (Exception e) {
			e.printStackTrace();
			return R.data(200, rmap, "exception:" + e.getMessage());
		}
		return R.data(rmap);
	}

	/**
	 * 根据用户获取部门列表
	 *
	 * @param bladeUser
	 * @return
	 */
	@GetMapping(value = "/userDeptList")
	@ApiOperation(value = "统计部门列表", notes = "统计部门列表")
	public R<List<HashMap<String, Object>>> getDeptList(BladeUser bladeUser) {
		String roles = bladeUser.getRoleId();
		String[] roleArr = roles.split(",");
		List<String> roleList = Arrays.asList(roleArr);
		List<HashMap<String, Object>> list = new ArrayList<>();
		List<Dept> deptList = null;
		String userDeptId = null;
		deptList = sysClient.getDeptList();
		R<UserInfo> userInfo = userClient.userInfo(Long.valueOf(bladeUser.getUserId()));
		if (userInfo.isSuccess()) {
			userDeptId = userInfo.getData().getUser().getDeptId();
		}
		HashMap<String, Object> deptMap;
		if (deptList != null && !deptList.isEmpty()) {
			for (Dept dept : deptList) {
				deptMap = new HashMap<>();
				deptMap.put("id", dept.getId());
				deptMap.put("name", dept.getDeptName());
				/*if (roleList.contains("9")||roleList.contains("10")) {
					if (userDeptId.equals(deptMap.get("id").toString())) {
						list.add(deptMap);
					}
				} else if (roleList.contains("8") && !roleList.contains("3")) {
					if (userDeptId.equals(deptMap.get("id").toString())) {
						list.add(deptMap);
					}
				} else if (roleList.contains("1") || roleList.contains("3") || roleList.contains("4") || roleList.contains("5")
					|| roleList.contains("6") || roleList.contains("7")) {
					list.add(deptMap);
				}*/
				list.add(deptMap);
			}
		}
		return R.data(list);
	}



}
